

import socket
import time

def measure_bandwidth(connection):
    start_time = time.time()
    total_bytes = 0

    while True:
        data = connection.recv(1024)  # 接收数据
        if not data:
            break
        total_bytes += len(data)

    end_time = time.time()
    elapsed_time = end_time - start_time
    bandwidth_mbps = (total_bytes * 8) / (elapsed_time * 1e6)  # 计算带宽，单位为 Mbps
    return bandwidth_mbps, elapsed_time

def task():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('', 9999)  # 空字符串表示监听所有可用的接口
    server_socket.bind(server_address)
    server_socket.listen(1)
    while True:
        print("等待客户端连接...")
        client_connection, client_address = server_socket.accept()
        print(f"客户端 {client_address} 已连接")

        bandwidth_mbps, elapsed_time = measure_bandwidth(client_connection)
        print(f"测量完成：实际可用带宽为 {bandwidth_mbps:.2f} Mbps，传输时间为 {elapsed_time:.2f} 秒")

        client_connection.close()
    server_socket.close()

if __name__ == "__main__":
    task()
